import os
import sys
import numpy as np
import cv2
import curses
import time

# 灰度字符
gray_num = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\、|()1{}[]?-_+~<>i!lI;: ,\"^`'.")
# 设定宽高比的校正比例，例如字符宽度是实际宽度的1.5倍
aspect_ratio = 1.5


def main(stdscr, videoPath: str):
    curses.curs_set(0)  # 隐藏光标
    stdscr.clear()

    # 初始化视频
    cap = cv2.VideoCapture(videoPath)
    success, frame = cap.read()

    # 设置帧延时（秒），可以根据需要调节
    frame_delay = 0.05

    while success:
        # 获取终端大小
        term_height, term_width = stdscr.getmaxyx()

        # 根据宽高比缩放终端尺寸，调整字符列数和行数
        new_width = int(term_width / aspect_ratio)
        new_height = term_height

        # 转换灰度图
        grayFrame = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)

        # 检查宽度和高度是否超出限制
        if new_width > 0 and new_height > 0:
            # 缩放到终端适应的大小
            fixFrame = cv2.resize(grayFrame, (new_width, new_height), interpolation=cv2.INTER_AREA)

            # 转换成字符画帧
            img_array = np.array(fixFrame, "f")
            ascii_frame = ""
            for line in img_array:
                for p in line:
                    index = int((p / 255) * (len(gray_num) - 1))
                    ascii_frame += gray_num[index]
                ascii_frame += "\n"

            # 显示字符画帧，检查窗口大小是否足够显示
            try:
                stdscr.addstr(0, 0, ascii_frame)
            except curses.error:
                pass  # 忽略显示超出窗口大小的错误

            stdscr.refresh()

        # 延时以控制播放速度
        time.sleep(frame_delay)

        # 读取下一帧
        success, frame = cap.read()

    cap.release()


if __name__ == "__main__":
    if len(sys.argv) > 1 and os.path.exists(sys.argv[1]):
        curses.wrapper(main, sys.argv[1])
    else:
        print("File not found.")